package com.episode.duetapi.shiro;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfiguration {
	
	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		
		//设置SecurityManager
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		
//		//如果不设置会自动寻找Web工程根目录下的"/login.jsp"页面
//		shiroFilterFactoryBean.setLoginUrl("/login");
//		//登录成功后要跳转的链接
//		shiroFilterFactoryBean.setSuccessUrl("/index");
//		//未授权界面
//		shiroFilterFactoryBean.setUnauthorizedUrl("/403");
		
		//自定义拦截器
		Map<String,Filter> filterMap = new LinkedHashMap<String,Filter>();
		shiroFilterFactoryBean.setFilters(filterMap);
		
		//权限控制map
		Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);		
		return shiroFilterFactoryBean;	      
	}
	
	@Bean
	public SecurityManager securityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		//设置realm
		securityManager.setRealm(myShiroRealm());		
		//注入记住管理器
		securityManager.setRememberMeManager(rememberMeManager());		
		return securityManager;
	}

	/**
	 * cookie管理对象；记住我功能
	 * */
	private CookieRememberMeManager rememberMeManager() {
		CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
		cookieRememberMeManager.setCookie(rememberMeCookie());
		//rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) 
		cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag=="));
		return cookieRememberMeManager;
	}

	@Bean
	public MyShiroRealm myShiroRealm() {
		
		return new MyShiroRealm();
	}
	
	/**
	 * cookie对象
	 * @return
	 * */
	public SimpleCookie rememberMeCookie() {
		//这个参数是cookie的名称，对应前端的checkbox的name
		SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
		simpleCookie.setMaxAge(2562000);
		return simpleCookie;
	}

}
